<template>
    <j-modal
      width="70%"
      :title="`账单匹配列表,流水未匹配金额：${this.maxPlanAmount}`"
      :maskClosable="false"
      :destroyOnClose="true"
      :visible.sync="editModalVisible"
      @cancel="handleCancleDbSync"
      @ok="handleDbSync"
    >
      <template slot="footer">
        <div style="text-align:right;">
          <a-button @click="handleCancleDbSync">关闭</a-button>
          <a-button type="primary" :loading="syncLoading" @click="handleDbSync">确定</a-button>
        </div>
      </template>
      <vxe-grid
        ref="xTable"
        border
        resizable
        keep-source
        height="300px"
        align="center"
        :columns="column"
        :data="dataSource"
        :edit-rules="validRules"
        :edit-config="{trigger: 'click', mode: 'row',autoClear:false, showStatus: true}"
        @checkbox-all="onSelectChange"
        @checkbox-change="onSelectChange"
      >
        <template v-slot:planAmount="{ row }">
          <a-input type="number" v-model="row.planAmount" />
        </template>
      </vxe-grid>
  </j-modal>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
export default {
  name: 'AuditManualListModal',
  data() {
    return {
      editModalVisible: false,
      disableSubmit: false,
      syncLoading: false,
      url: {
        list: '/community/bill/list',
        autoAmount: '/community/cash/autoAmount',
        addAmount: '/community/cash/addAmount'
      },
      dataSource: [],
      column: [
        { type: 'checkbox', width: 50 },
        { type: 'seq', width: 40 },
        { title: '账单编号', field: 'billCode' },
        { title: '账单类型', field: 'billType', slots: { default: ({ row }) => {
          return filterDictTextByCache('xy_park_bill_type', row.billType)
        } }},
        { title: '应收/应付日期', field: 'dueDate' },
        { title: '账单金额', field: 'amount' },
        { title: '已分配金额', field: 'checkAmount' },
        { title: '未匹配金额', field: 'surplusAmount', slots: { default: ({ row }) => {
          return row.checkAmount ? row.amount - row.checkAmount : row.amount
        } }},
        { title: '分配金额', field: 'planAmount', editRender: {}, slots: { edit: 'planAmount', default: ({ row }) => {
          return row.planAmount
        } }},
        { title: '关联合同', field: 'contractCode' }
      ],
      validRules: {
        planAmount: [
          { required: true, message: '请填写分配金额', trigger: 'change' },
          { validator: this.planAmountValid, trigger: 'change' }
        ]
      },
      selectedRowKeys: [],
      selectionRows: [],
      formData: {}
    }
  },
  methods: {
    planAmountValid({ cellValue, row }) {
      if (Number(cellValue) <= 0) {
        return new Error('分配金额不能小于等于0')
      }
      if (Number(cellValue) > (row.checkAmount ? row.amount - row.checkAmount : row.amount)) {
        return new Error('分配金额不能大于未匹配金额')
      }
    },
    edit(row) {
      this.formData = row
      this.editModalVisible = true
      this.maxPlanAmount = this.formData.checkAmount ? this.formData.amount - this.formData.checkAmount : this.formData.amount
      this.loadData()
    },
    loadData() {
      getAction(this.url.list, {
        costType: this.formData.costType,
        ownerCode: this.formData.ownerCode,
        billType: this.formData.cashType,
        customerAccount: this.formData.customerAccount,
        clearStatus: '!3',
        billStatus: '3',
        pageNo: 1,
        pageSize: 9999
      }).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.dataSource.forEach(item => {
            item.planAmount = item.checkAmount ? item.amount - item.checkAmount : item.amount
          })
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleCancleDbSync() {
      this.editModalVisible = false
    },
    async handleDbSync() {
      const $table = this.$refs.xTable
      const selectRecords = $table.getCheckboxRecords()
      if (selectRecords.length > 0) {
        const errMap = await $table.validate(selectRecords).catch(errMap => errMap)
        if (!errMap) {
          var total = 0
          selectRecords.forEach(item => {
            total += item.planAmount
          })
          if (total > this.maxPlanAmount) {
            this.$message.warning(`总分配金额不能大于流水未匹配金额${this.maxPlanAmount}`)
            return false
          }
          this.save(selectRecords)
        }
      } else {
        this.$message.warning('未选中数据！')
      }
    },
    save(selectRecords) {
      this.syncLoading = true
      const data = []
      selectRecords.forEach(item => {
        data.push({
          billCode: item.billCode,
          cashCode: this.formData.cashCode,
          checkAmount: item.planAmount
        })
      })
      postAction(this.url.addAmount, data).then(res => {
        if (res.success) {
          this.editModalVisible = false
          this.$message.success('分配成功')
          this.$emit('ok')
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.syncLoading = false
      })
    },
    onSelectChange({ records }) {
      this.selectedRowKeys = []
      records.forEach(item => {
        this.selectedRowKeys.push(item.id)
      })
      this.selectionRows = records
    }
  }
}
</script>
<style lang="less">

</style>
